import { defineStore } from 'pinia'
import { reactive } from 'vue'
import { queryTopCategorys, queryParamsByMainOrganId, queryParamByOrganId, queryCategoryTreeByParentId, getMockDetail } from '@/api/medical'

export const useMedicalStore = defineStore('medical', {
  state: () => ({
    organs: [], // 器官列表
    selectedOrgan: null, // 选中的器官（保留兼容性）
    selectedOrgans: [], // 选中的多个器官
    selectedOrgansData: [], // 选中器官的数据（包含树形菜单）
    attributeMenu: [], // 属性菜单（保留兼容性）
    selectedAttribute: null, // 选中的属性
    selectedNodes: [], // 选中的节点
    selectedLeafNodes: [], // 选中的叶子节点（多选）
    attributePath: [], // 属性路径
    attributeDetail: null, // 属性详情
    formData: {}, // 表单数据

  }),
  
  actions: {
    // 获取器官列表
    async fetchOrgans() {
      try {
        const res = await queryTopCategorys()
        console.log('器官列表API响应:', res)
        if (res && (res.data || res.length)) {
          this.organs = res.data || res
          console.log('成功获取器官列表:', this.organs)
        } else {
          throw new Error('API返回数据为空')
        }
      } catch (error) {
        console.error('获取器官列表失败，使用模拟数据:', error.message)
        // 如果API调用失败，使用模拟数据作为备选
        this.organs = [
          { id: 1, name: '胃' },
          { id: 2, name: '肠' },
          { id: 3, name: '十二指肠' }
        ]
        console.log('已加载模拟器官数据:', this.organs)
      }
    },
    
    // 选择器官（保留兼容性）
    selectOrgan(organ) {
      this.selectedOrgan = organ
      this.fetchAttributeMenu(organ.id)
    },

    // 选择多个器官
    async selectMultipleOrgans(organIds) {
      console.log('选择多个器官:', organIds)
      
      // 更新选中的器官列表
      this.selectedOrgans = organIds.map(id => 
        this.organs.find(organ => organ.id === id)
      ).filter(Boolean)
      
      // 清空之前的器官数据
      this.selectedOrgansData = []
      
      // 为每个选中的器官获取树形菜单数据
      for (const organId of organIds) {
        const organ = this.organs.find(o => o.id === organId)
        if (organ) {
          await this.fetchAttributeMenuForOrgan(organId, organ.name)
        }
      }
    },
    
    // 转换API数据结构为组件所需格式
    transformTreeData(node) {
      if (!node) return null
      
      const transformed = {
        id: node.id,
        name: node.name,
        level: node.level,
        parentId: node.parentId,
        sort: node.sort,
        children: []
      }
      
      // 递归转换子节点
      if (node.childrenCategorys && node.childrenCategorys.length > 0) {
        transformed.children = node.childrenCategorys.map(child => this.transformTreeData(child))
      }
      
      return transformed
    },

    // 获取属性菜单
    async fetchAttributeMenu(organId) {
      try {
        console.log('正在获取器官ID为', organId, '的属性菜单')
        const res = await queryCategoryTreeByParentId({ organId })
        console.log('树形菜单API响应:', res)
        if (res && res.data) {
          // 转换数据结构：API返回单个对象，需要转换为数组格式
          const transformedData = this.transformTreeData(res.data)
          this.attributeMenu = transformedData ? [transformedData] : []
          console.log('成功获取并转换属性菜单:', this.attributeMenu)
        } else {
          throw new Error('API返回数据为空')
        }
      } catch (error) {
        console.error('获取属性菜单失败，使用模拟数据:', error.message)
        // 如果API调用失败，使用模拟数据作为备选
        if (organId === 1) { // 胃
          this.attributeMenu = [
            { id: 1, name: '胃', parentId: null, children: [
                { id: 100, name: '食管', parentId: 1, children: [
                    { id: 10000, name: '咽喉', parentId: 100, children: [] },
                    { id: 10001, name: '上段', parentId: 100, children: [
                          { id: 1000000, name: '正常描述', parentId: 10001, children: [] },
                          { id: 1000001, name: '糜烂性食管炎', parentId: 10001, children: [] },
                          { id: 1000002, name: '浅表性食管炎', parentId: 10001, children: [] },
                          { id: 1000003, name: '反流性食管炎', parentId: 10001, children: [] }
                      ] }
                  ] },
                  { id: 101, name: '贲门', parentId: 1, children: [] },
                  { id: 102, name: '胃底', parentId: 1, children: [] }
              ] }
          ]
        } else if (organId === 2) { // 肠
          this.attributeMenu = [
            { id: 6, name: '结肠', parentId: null, children: [] },
            { id: 7, name: '直肠', parentId: null, children: [] }
          ]
        } else { // 十二指肠
          this.attributeMenu = [
            { id: 8, name: '球部', parentId: null, children: [] },
            { id: 9, name: '降部', parentId: null, children: [] }
          ]
        }
        console.log('已加载器官ID', organId, '的模拟属性菜单:', this.attributeMenu)
      }
    },

    // 为特定器官获取属性菜单
    async fetchAttributeMenuForOrgan(organId, organName) {
      try {
        console.log('正在获取器官ID为', organId, '的属性菜单')
        const res = await queryCategoryTreeByParentId({ organId })
        console.log('器官', organName, '的树形菜单API响应:', res)
        
        if (res && res.data) {
          // 转换数据结构
          const transformedData = this.transformTreeData(res.data)
          const attributeMenu = transformedData ? [transformedData] : []
          
          // 添加到选中器官数据列表
          this.selectedOrgansData.push({
            organId: organId,
            organName: organName,
            attributeMenu: attributeMenu
          })
          
          console.log('成功获取器官', organName, '的属性菜单:', attributeMenu)
        } else {
          throw new Error('API返回数据为空')
        }
      } catch (error) {
        console.error('获取器官', organName, '的属性菜单失败，使用模拟数据:', error.message)
        
        // 使用模拟数据
        let mockAttributeMenu = []
        if (organId === 1) { // 胃
          mockAttributeMenu = [
            { id: 1, name: '胃', parentId: null, children: [
                { id: 100, name: '食管', parentId: 1, children: [
                    { id: 10000, name: '咽喉', parentId: 100, children: [] },
                    { id: 10001, name: '上段', parentId: 100, children: [
                          { id: 1000000, name: '正常描述', parentId: 10001, children: [] },
                          { id: 1000001, name: '糜烂性食管炎', parentId: 10001, children: [] },
                          { id: 1000002, name: '浅表性食管炎', parentId: 10001, children: [] },
                          { id: 1000003, name: '反流性食管炎', parentId: 10001, children: [] }
                      ] }
                  ] },
                  { id: 101, name: '贲门', parentId: 1, children: [] },
                  { id: 102, name: '胃底', parentId: 1, children: [] }
              ] }
          ]
        } else if (organId === 2) { // 肠
          mockAttributeMenu = [
            { id: 6, name: '结肠', parentId: null, children: [] },
            { id: 7, name: '直肠', parentId: null, children: [] }
          ]
        } else { // 十二指肠
          mockAttributeMenu = [
            { id: 8, name: '球部', parentId: null, children: [] },
            { id: 9, name: '降部', parentId: null, children: [] }
          ]
        }
        
        // 添加到选中器官数据列表
        this.selectedOrgansData.push({
          organId: organId,
          organName: organName,
          attributeMenu: mockAttributeMenu
        })
        
        console.log('已加载器官', organName, '的模拟属性菜单:', mockAttributeMenu)
      }
    },
    
    // 选择属性
    selectAttribute(attribute, organId = null) {
      this.selectedAttribute = attribute
      this.fetchAttributeDetail(attribute.id)
      
      // 更新属性路径
      this.updateAttributePath(attribute, organId)
    },
    
    // 更新属性路径
    updateAttributePath(attribute, organId = null) {
      const path = []
      let current = attribute
      
      // 向上遍历获取完整路径
      while (current) {
        path.unshift({
          id: current.id,
          name: current.name
        })
        
        if (current.parentId) {
          if (organId) {
            // 在指定器官的数据中查找
            const organData = this.selectedOrgansData.find(data => data.organId === organId)
            current = organData ? this.findNodeById(organData.attributeMenu, current.parentId) : null
          } else {
            // 兼容性：在原有数据中查找
            current = this.findNodeById(this.attributeMenu, current.parentId)
          }
        } else {
          break
        }
      }
      
      this.attributePath = path
    },
    
    // 根据ID查找节点
    findNodeById(nodes, id) {
      for (const node of nodes) {
        if (node.id === id) {
          return node
        }
        if (node.children && node.children.length > 0) {
          const found = this.findNodeById(node.children, id)
          if (found) {
            return found
          }
        }
      }
      return null
    },
    
    // 构建节点路径
    buildNodePath(node, treeData) {
      const path = []
      let current = node
      
      while (current) {
        path.unshift({
          id: current.id,
          name: current.name
        })
        
        if (current.parentId) {
          current = this.findNodeById(treeData, current.parentId)
        } else {
          break
        }
      }
      
      return path
    },
    
    // 更新选中的节点
    updateSelectedNodes(nodes) {
      this.selectedNodes = nodes
    },
    
    // 获取属性详情
    async fetchAttributeDetail(attributeId) {
      try {
        const res = await queryParamByOrganId(attributeId)
        this.attributeDetail = res.data || res
      } catch (error) {
        console.error('获取属性详情失败:', error)
        // 如果API调用失败，使用模拟数据作为备选
        let detail = null
        
        // 根据不同的属性ID返回不同的表单配置
        switch(attributeId) {
          case 1000000: // 正常描述 - 输入框
            detail = {
              title: '正常描述',
              type: 'input',
              options: [
                { value: '' }
              ],
              units: []
            }
            break
          case 1000001: // 糜烂性食管炎 - 单选
            detail = {
              title: '糜烂性食管炎',
              type: 'radio',
              options: [
                { value: '轻度', sort: 0, checked: 0 },
                { value: '中度', sort: 1, checked: 0 },
                { value: '重度', sort: 2, checked: 0 }
              ],
              units: []
            }
            break
          case 1000002: // 浅表性食管炎 - 多选
            detail = {
              title: '浅表性食管炎',
              type: 'checkbox',
              options: [
                { value: '前壁', sort: 0, checked: 0 },
                { value: '中部', sort: 1, checked: 0 },
                { value: '后壁', sort: 2, checked: 0 }
              ],
              units: []
            }
            break
          case 1000003: // 反流性食管炎 - 输入框带单位
            detail = {
              title: '反流性食管炎',
              type: 'input_with_unit',
              options: [
                { value: '' }
              ],
              units: [
                { value: 'cm' }
              ]
            }
            break
          case 100: // 食管 - 面积计算
            detail = {
              title: '食管面积',
              type: 'area',
              options: [
                { value: '', sort: 0 },
                { value: '', sort: 1 }
              ],
              units: [
                { value: 'cm', sort: 0, checked: 0 },
                { value: 'mm', sort: 1, checked: 0 }
              ]
            }
            break
          case 101: // 贲门 - 体积计算
            detail = {
              title: '贲门体积',
              type: 'volume',
              options: [
                { value: '', sort: 0 },
                { value: '', sort: 1 }
              ],
              units: []
            }
            break
          default:
            detail = {
              title: '默认表单',
              type: 'input',
              options: [
                { value: '' }
              ],
              units: []
            }
        }
        
        this.attributeDetail = detail
      }
    },
    
    // 更新表单数据
    updateFormData(key, value) {
      this.formData[key] = value
    },
    


    // 导航到指定层级
    navigateToLevel(levelIndex) {
      if (levelIndex >= 0 && levelIndex < this.attributePath.length) {
        const targetAttribute = this.attributePath[levelIndex]
        this.selectedAttribute = targetAttribute
        this.fetchAttributeDetail(targetAttribute.id)
        
        // 更新路径，只保留到目标层级的路径
        this.attributePath = this.attributePath.slice(0, levelIndex + 1)
      }
    },



    // 添加叶子节点到多选列表
    addLeafNode(node, organId = null) {
      const exists = this.selectedLeafNodes.find(item => item.id === node.id)
      if (!exists) {
        // 构建节点路径
        let nodePath = []
        if (organId) {
          // 在多器官模式下，构建包含器官信息的路径
          const organData = this.selectedOrgansData.find(data => data.organId === organId)
          if (organData) {
            nodePath = this.buildNodePath(node, organData.attributeMenu)
          }
        } else {
          // 兼容性：使用当前属性路径
          nodePath = node.path || [...this.attributePath]
        }
        
        this.selectedLeafNodes.push({
          ...node,
          organId: organId, // 添加器官ID信息
          path: nodePath,
          detail: null,
          formData: reactive({}) // 使用reactive创建响应式表单数据
        })
        // 获取该节点的详情
        this.fetchLeafNodeDetail(node.id)
      }
    },

    // 移除叶子节点
    removeLeafNode(nodeId) {
      const index = this.selectedLeafNodes.findIndex(item => item.id === nodeId)
      if (index !== -1) {
        this.selectedLeafNodes.splice(index, 1)
      }
    },

    // 取消勾选叶子节点（用于左侧菜单联动）
    uncheckLeafNode(nodeId, organId) {
      // 从selectedLeafNodes中移除
      this.removeLeafNode(nodeId)
      
      // 返回节点信息供左侧菜单取消勾选
      return { nodeId, organId }
    },

    // 清空所有选中的叶子节点
    clearLeafNodes() {
      this.selectedLeafNodes = []
    },

    // 获取叶子节点详情
    async fetchLeafNodeDetail(nodeId) {
      try {
        // 修复：将nodeId包装为API需要的对象格式
        const res = await queryParamByOrganId({ organId: nodeId })
        const detail = res.data || res
        
        // 更新对应叶子节点的详情
        const nodeIndex = this.selectedLeafNodes.findIndex(item => item.id === nodeId)
        if (nodeIndex !== -1) {
          this.selectedLeafNodes[nodeIndex].detail = detail
        }
      } catch (error) {
        console.error('获取叶子节点详情失败:', error)
        // 使用模拟数据
        try {
          const mockRes = await this.getMockDetail(nodeId)
          const detail = mockRes.data || mockRes
          const nodeIndex = this.selectedLeafNodes.findIndex(item => item.id === nodeId)
          if (nodeIndex !== -1) {
            this.selectedLeafNodes[nodeIndex].detail = detail
          }
        } catch (mockError) {
          console.error('获取模拟数据失败:', mockError)
        }
      }
    },

    // 获取模拟详情数据
    getMockDetail(organId) {
      return getMockDetail(organId)
    }
  }
})